package com.demo03_feed.controller;


import com.demo03_feed.bean.Video;
import com.demo03_feed.client.VideoServiceClient;
import com.demo03_feed.exception.FeignException;
import com.demo03_feed.util.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/feed")
@RequiredArgsConstructor
@Slf4j
public class FeedController {
    private final RedisTemplate<String, String> redisTemplate;
    private final VideoServiceClient videoServiceClient;

    @GetMapping
    public ResponseEntity<ApiResponse<List<Video>>> getFeed(HttpServletRequest request,
                               @RequestParam(defaultValue = "0") @Min(0) Long page,
                               @RequestParam(defaultValue = "10") @Min(1) @Max(100) Long size) {
        long startTime = System.currentTimeMillis();
        
        // 从请求头中获取用户ID（由API网关解析JWT Token后传递）
        String userIdStr = request.getHeader("user-id");
        if (userIdStr == null || userIdStr.isEmpty()) {
            throw new RuntimeException("缺少用户ID");
        }
        
        Long userId = Long.parseLong(userIdStr);
        
        log.info("用户[{}]请求Feed, page={}, size={}", userId, page, size);
        
        // 参数校验
        if (page < 0 || size <= 0 || size > 100) {
            throw new IllegalArgumentException("分页参数不合法");
        }
        
        try {
            // 计算起始位置
            Long start = page * size;
            
            // 1. 从Redis中分页获取视频ID
            String feedKey = "feed:" + userId;
            Set<String> videoIds = redisTemplate.opsForZSet()
                    .reverseRange(feedKey, start, start + size - 1);

            // 2. 根据videoIds去视频服务批量查询视频详情
            List<Video> videoList;
            if (videoIds == null || videoIds.isEmpty()) {
                videoList = new ArrayList<>();
            } else {
                videoList = batchGetVideosWithFallback(new ArrayList<>(videoIds));
            }
            
            log.info("用户[{}]Feed请求完成, 耗时: {}ms, 返回{}条视频", 
                    userId, System.currentTimeMillis() - startTime, videoList.size());
            
            return ResponseEntity.ok(ApiResponse.success(videoList));
        } catch (Exception e) {
            log.error("用户[{}]Feed请求异常, 耗时: {}ms", 
                    userId, System.currentTimeMillis() - startTime, e);
            throw e;
        }
    }
    
    private List<Video> batchGetVideosWithFallback(List<String> videoIds) {
        try {
            return videoServiceClient.getVideosByIds(videoIds);
        } catch (Exception e) {
            log.warn("视频服务调用失败，返回空结果: {}", e.getMessage());
            throw new FeignException("依赖服务暂时不可用", e);
        }
    }
}